package com.team.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.team.dao.FolderDao;
import com.team.dao.UserDao;
import com.team.entity.Folder;
import com.team.entity.Project;
import com.team.entity.User;
import com.team.util.Const;
import com.team.util.StringUtil;
import com.team.util.TUtil;

public class NewFolderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_m");
		
		if("save".equals(method)){
			saveFolder(request,response);
		}else if("select".equals(method)){
			selectAllFolders(request,response);
			
		}else {
			response.sendError(404,"request a error path");
			return ;
		}
		
		
	}
	private void selectAllFolders(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		FolderDao fd = new FolderDao();
		List<Folder> list = new ArrayList<Folder>();
		list = fd.selectAllFolders();
		HttpSession session = request.getSession();
		session.setAttribute(Const.SESSION_FOLDER, list);
		response.sendRedirect("fileshare.jsp");
		return ;
	}
	private void saveFolder(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String folderName = request.getParameter("folderName");
		String folderCreater = request.getParameter("folderCreater");
		
		if(StringUtil.isEmpty(folderName)||StringUtil.isEmpty(folderCreater)){
			response.sendRedirect("newFolder.jsp?code=1001");
			return ;
		}
		HttpSession session = request.getSession();
		FolderDao fd = new FolderDao();
		Project project = (Project) session.getAttribute(Const.SESSION_PROJ);
		int projId = project.getId();
		UserDao ud = new UserDao();
		User user = ud.selectByName(folderCreater);
		if(user == null){
			response.sendRedirect("newFolder.jsp?code=1004");
			return ;
		}
		Folder folder = new Folder();
		folder.setCreatetime(TUtil.getNow());
		folder.setFiletypename(folderName);
		folder.setProjId(projId);
		folder.setUserId(user.getId());//creater may not be loginer
		int num = fd.saveFolder(folder);
		if(num > 0){
			response.sendRedirect("newFolder.jspx?_m=select");
			return ;
		}else {
			response.sendRedirect("newFolder.jsp?code=1002");
			return ;
		}
	}
}
